//
//  LoginViewController.m
//  OAProject
//
//  Created by yhj on 2017/2/21.
//  Copyright © 2017年 cdnunion. All rights reserved.
//  登录主界面

#import "LoginViewController.h"
#import "CYLTabBarControllerConfig.h"
#import "RequestTool.h"

@interface LoginViewController ()<UITextFieldDelegate>

@property(nonatomic,strong)LabelTextFieldView *nameView;

@property(nonatomic,strong)LabelTextFieldView *pdView;

@end

@implementation LoginViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    UIImageView *loginBg=[[UIImageView alloc]initWithFrame:self.view.bounds];
    loginBg.userInteractionEnabled=YES;
    loginBg.backgroundColor=BGColor;
    loginBg.image=[UIImage imageNamed:@"loginBg"];
    [self.view addSubview:loginBg];


    UIView *loginView=[[UIView alloc]initWithFrame:CGRectMake(kmargin*5,APPH/2-kmargin*10,APPW-kmargin*10,kmargin*10+1)];
    loginView.backgroundColor=ClearColor;
    ViewBorderRadius(loginView,kmargin/2,1,LightGreyColor);
    [loginBg addSubview:loginView];


    _nameView=[[LabelTextFieldView alloc]initWithImage:@"nameIcon" placeholder:@"请输入用户名"];
    //[[LabelTextFieldView alloc]initWithTitle:@"用户名" placeholder:@"请输入用户名"];
    _nameView.frame=CGRectMake(0,0,APPW-kmargin*10,kmargin*5);
    [loginView addSubview:_nameView];
    _nameView.textField.textColor=LightGreyColor;
    _nameView.textField.font=Font_Number(15);
    _nameView.textField.keyboardType=UIKeyboardTypeDefault;
    _nameView.textField.delegate=self;


    UIView *lineView=[[UIView alloc]initWithFrame:CGRectMake(0,kmargin*5,APPW-kmargin*10,1)];
    lineView.backgroundColor=LightGreyColor;
    [loginView addSubview:lineView];


    _pdView=[[LabelTextFieldView alloc]initWithImage:@"passwordIcon" placeholder:@"请输入密码"];
    //[[LabelTextFieldView alloc]initWithTitle:@"密  码" placeholder:@"请输入密码"];
    _pdView.frame=CGRectMake(0,kmargin*5+1,APPW-kmargin*10,kmargin*5);
    _pdView.textField.secureTextEntry=YES;
    [loginView addSubview:_pdView];
    _pdView.textField.textColor=LightGreyColor;
    _pdView.textField.font=Font_Number(15);
    _pdView.textField.keyboardType=UIKeyboardTypeDefault;
    _pdView.textField.delegate=self;

   UIButton *loginBtn=[AppUI createButtonWithText:@"登  录" andWithTextColor:WhiteColor andWithFontfloat:20 andWithBtnAction:^{

       [self loginBtnEvent];

   }];
    ViewBorderRadius(loginBtn,kmargin/2,1,ClearColor);
    loginBtn.frame=CGRectMake(kmargin*5,APPH/2+kmargin*3,APPW-kmargin*10,kmargin*5);
    loginBtn.backgroundColor=MainColor;
    [loginBg addSubview:loginBtn];

}

-(void)loginBtnEvent
{
    // 系统去首尾空格方法，使用NSString中的str = [str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]方法只是去掉左右两边的空格；
    NSString *nameStr=[self.nameView.textField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    NSString *psdStr=[self.pdView.textField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    NSDictionary *params=@{
                           @"admin_name":nameStr,
                           @"code":psdStr
                           };
    [RequestTool PostCallBack:LoginURL parameter:[params configParameters] success:^(id responseObj) {

        NSLog(@"responseObj---%@  00-----%@",responseObj,responseObj[@"error"]);

        if ([responseObj[@"rt"] isEqual:@(1)])
        {
            [self.view makeToast:responseObj[@"error"] duration:1 position:CSToastPositionCenter];

            dispatch_after(dispatch_time(DISPATCH_TIME_NOW,(int64_t)(1.0*NSEC_PER_SEC)), dispatch_get_main_queue(), ^{

                // 存储用户密码以后用
                [Util saveObjectToUserDefault:_pdView.textField.text forKey:@"passwd"];

                [Util saveObjectToUserDefault:@"YES" forKey:ISLogin];

                [Util saveObjectToUserDefault:responseObj[@"token"] forKey:@"Token"];
                [Util saveObjectToUserDefault:responseObj[@"vathome"][@"token"] forKey:@"TToken"];


                // 云存储信息
                [Util saveObjectToUserDefault:responseObj[@"vathome"][@"storage"][@"access_key"] forKey:@"access_key"];
                [Util saveObjectToUserDefault:responseObj[@"vathome"][@"storage"][@"access_secret"] forKey:@"access_secret"];
                [Util saveObjectToUserDefault:responseObj[@"vathome"][@"storage"][@"bucket"] forKey:@"bucket"];
                [Util saveObjectToUserDefault:responseObj[@"vathome"][@"storage"][@"host"] forKey:@"host"];

                [self uploadToken];

                AppDelegate *delegate=(AppDelegate *)[UIApplication sharedApplication].delegate;
                delegate.window.rootViewController=[[CYLTabBarControllerConfig new]tabBarController];
            });
        }
        else
        {
            [self.view makeToast:responseObj[@"error"] duration:1 position:CSToastPositionCenter];
        }

    } failure:^(NSError *error) {

        NSLog(@"sdsdhfd9000---%@",error);
        
        // 登录失败处理
        NSData *errorData=[[error userInfo] objectForKey:@"com.alamofire.serialization.response.error.data"];
        id jsonObject=[NSJSONSerialization JSONObjectWithData:errorData options:NSJSONReadingMutableLeaves error:nil];
        if ([jsonObject[@"rt"] isEqual:@(0)])
        {
          [self.view makeToast:jsonObject[@"error"] duration:1 position:CSToastPositionCenter];
        }
    }];
}


-(void)uploadToken
{
    NSDictionary *params=@{
                           @"MYIDCODE":[Util getUserDefaultObjectForKey:@"Token"],
                           @"token":[Util getUserDefaultObjectForKey:@"clientId"]
                           };
    NSLog(@"sdjjhdfj---%@",params);

    [RequestTool PostCallBack:Upload_TokenUrl parameter:params success:^(id responseObj) {

        NSLog(@"sdhhjshjdf0---%@ ---%@",responseObj,responseObj[@"error"]);

        // token 成功
        if ([responseObj[@"rt"] isEqual:@(1)])
        {

        }
        else
        {
            [AlertLabel hudShowText:responseObj[@"error"]];
        }

    } failure:^(NSError *error) {
        
    }];
}


-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];

    return YES;
}


@end
